package com.katesoft.scale4j.demo.services;

import org.apache.commons.lang.StringUtils;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.scope.context.StepContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.katesoft.scale4j.common.services.IBeanNameReferences;

public class RatesPopulator {
   public static void main(String[] args) {
      final ClassPathXmlApplicationContext config = new ClassPathXmlApplicationContext(
               "META-INF/spring/currencies-app-context.xml");
      TransactionTemplate transactionTemplate = (TransactionTemplate) config
               .getBean(IBeanNameReferences.TRANSACTION_TEMPLATE);
      try {
         transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(
                     @SuppressWarnings("unused") TransactionStatus status) {
               AvailableCurrenciesTasklet tasklet1 = config.getBean("available.currencies.tasklet",
                        AvailableCurrenciesTasklet.class);
               tasklet1.execute(null, null);
            }
         });
         for (int i = 2010; i <= 2010; i++) {
            for (int j = 1; j <= 12; j++) {
               final String date = String.format("%s-%s-01", i,
                        StringUtils.leftPad(Integer.valueOf(j).toString(), 2, "0"));
               transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                  @Override
                  protected void doInTransactionWithoutResult(
                           @SuppressWarnings("unused") TransactionStatus status) {
                     CurrencyExchangeRatesTasklet tasklet2 = config
                              .getBean("currency.exchange.rates.tasklet",
                                       CurrencyExchangeRatesTasklet.class);
                     ChunkContext chunkContext = new ChunkContext(new StepContext(
                              new StepExecution("step-1", new JobExecution(1L))));
                     chunkContext.getStepContext().getStepExecution().getJobExecution()
                              .getExecutionContext().put("date", date);
                     tasklet2.execute(null, chunkContext);
                  }
               });
            }
         }
      } finally {
         config.destroy();
         System.exit(0);
      }
   }
}
